// pages/login/login.js
const authManager = require('../../utils/auth.js')
const api = require('../../utils/api.js')

Page({
  data: {
    username: '',
    password: '',
    loginLoading: false,
    loginStep: 1, // 1: 登录按钮, 2: 身份绑定
    needBind: false,
    userInfo: null,
    // 身份绑定表单
    bindForm: {
      realName: '',
      idCard: '',
      studentNo: '',
      schoolId: '',
      classId: ''
    },
    // 学校和班级选项
    schools: [],
    classes: [],
    selectedSchoolIndex: -1,
    selectedClassIndex: -1,
    errors: {}
  },

  onLoad() {
    // 检查登录状态
    const loginStatus = authManager.checkLoginStatus()
    if (loginStatus.isLoggedIn) {
      if (loginStatus.needBind) {
        // 需要身份绑定
        this.setData({
          loginStep: 2,
          needBind: true,
          userInfo: loginStatus.userInfo
        })
        this.loadSchools()
      } else {
        // 已完成绑定，跳转到首页
        wx.switchTab({
          url: '/pages/home/home'
        })
      }
    }
  },

  onInputUsername(e) {
    this.setData({
      username: e.detail
    });
  },

  onInputPassword(e) {
    this.setData({
      password: e.detail
    });
  },

  // 账号密码登录（保留原有功能）
  handleLogin() {
    const { username, password } = this.data;
    
    if (!username || !password) {
      wx.showToast({
        title: '请输入用户名和密码',
        icon: 'none'
      });
      return;
    }

    this.setData({ loginLoading: true });

    // 模拟网络请求延迟
    setTimeout(() => {
      // 这里添加实际的登录验证逻辑
      if (username === 'admin' && password === '123456') {
        wx.setStorageSync('isLoggedIn', true);
        wx.setStorageSync('userInfo', { 
          username,
          avatar: '/assets/default-avatar.png',
          loginTime: new Date().toISOString()
        });
        
        this.setData({ loginLoading: false });
        
        wx.showToast({
          title: '登录成功',
          icon: 'success',
          duration: 1500,
          success: () => {
            setTimeout(() => {
              wx.reLaunch({
                url: '/pages/home/home'
              });
            }, 1500);
          }
        });
      } else {
        this.setData({ loginLoading: false });
        wx.showToast({
          title: '用户名或密码错误',
          icon: 'none'
        });
      }
    }, 1500);
  },

  // 微信一键登录（新的实现）
  async handleWechatLogin(e) {
    // 直接获取用户信息
    if (!e.detail.userInfo) {
      wx.showToast({
        title: '需要授权才能登录',
        icon: 'none'
      });
      return;
    }

    this.setData({ loginLoading: true });

    try {
      const result = await authManager.wxLogin();
      
      if (result.success) {
        wx.showToast({
          title: '登录成功',
          icon: 'success'
        });
        
        if (result.needBind) {
          // 需要身份绑定
          this.setData({
            loginStep: 2,
            needBind: true,
            userInfo: result.userInfo,
            loginLoading: false
          });
          this.loadSchools();
        } else {
          // 登录完成，跳转到首页
          setTimeout(() => {
            wx.switchTab({
              url: '/pages/home/home'
            });
          }, 1500);
        }
      } else {
        wx.showToast({
          title: result.error || '登录失败',
          icon: 'error'
        });
      }
    } catch (error) {
      console.error('登录失败:', error);
      wx.showToast({
        title: '登录失败',
        icon: 'error'
      });
    } finally {
      this.setData({ loginLoading: false });
    }
  },

  /**
   * 加载学校列表
   */
  async loadSchools() {
    try {
      const result = await api.school.getList();
      
      if (result.code === 200) {
        this.setData({
          schools: result.data || []
        });
      }
    } catch (error) {
      console.error('获取学校列表失败:', error);
    }
  },

  /**
   * 选择学校
   */
  onSchoolChange(e) {
    const index = e.detail.value;
    const school = this.data.schools[index];
    
    this.setData({
      selectedSchoolIndex: index,
      'bindForm.schoolId': school.schoolId,
      selectedClassIndex: -1,
      'bindForm.classId': '',
      classes: []
    });
    
    // 加载班级列表
    this.loadClasses(school.schoolId);
  },

  /**
   * 加载班级列表
   */
  async loadClasses(schoolId) {
    try {
      const result = await api.school.getClasses(schoolId);
      
      if (result.code === 200) {
        this.setData({
          classes: result.data || []
        });
      }
    } catch (error) {
      console.error('获取班级列表失败:', error);
    }
  },

  /**
   * 选择班级
   */
  onClassChange(e) {
    const index = e.detail.value;
    const classInfo = this.data.classes[index];
    
    this.setData({
      selectedClassIndex: index,
      'bindForm.classId': classInfo.classId
    });
  },

  /**
   * 表单输入
   */
  onFormInput(e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    
    this.setData({
      [`bindForm.${field}`]: value
    });
  },

  /**
   * 验证身份绑定表单
   */
  validateBindForm() {
    const { bindForm } = this.data;
    const errors = {};
    
    if (!bindForm.realName.trim()) {
      errors.realName = '请输入真实姓名';
    }
    
    if (!bindForm.idCard.trim()) {
      errors.idCard = '请输入身份证号';
    } else if (!/^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(bindForm.idCard)) {
      errors.idCard = '身份证号格式不正确';
    }
    
    if (!bindForm.studentNo.trim()) {
      errors.studentNo = '请输入学号';
    }
    
    if (!bindForm.schoolId) {
      errors.schoolId = '请选择学校';
    }
    
    if (!bindForm.classId) {
      errors.classId = '请选择班级';
    }
    
    this.setData({ errors });
    
    return Object.keys(errors).length === 0;
  },

  /**
   * 提交身份绑定
   */
  async submitBind() {
    if (!this.validateBindForm()) {
      wx.showToast({
        title: '请完善身份信息',
        icon: 'error'
      });
      return;
    }
    
    this.setData({ loginLoading: true });
    
    try {
      const result = await authManager.bindIdentity(this.data.bindForm);
      
      if (result.success) {
        wx.showToast({
          title: '身份绑定成功',
          icon: 'success'
        });
        
        // 跳转到首页
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/home/home'
          });
        }, 1500);
      } else {
        wx.showToast({
          title: result.error || '绑定失败',
          icon: 'error'
        });
      }
    } catch (error) {
      console.error('身份绑定失败:', error);
      wx.showToast({
        title: '绑定失败',
        icon: 'error'
      });
    } finally {
      this.setData({ loginLoading: false });
    }
  },

  /**
   * 返回登录步骤
   */
  backToLogin() {
    this.setData({
      loginStep: 1,
      needBind: false,
      userInfo: null,
      bindForm: {
        realName: '',
        idCard: '',
        studentNo: '',
        schoolId: '',
        classId: ''
      },
      selectedSchoolIndex: -1,
      selectedClassIndex: -1,
      errors: {}
    });
  }
});
